﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace viBook.Models
{
    public class CategoryRepository:ICategoryRepository
    {
        private readonly viBookContext context = new viBookContext();
        public IQueryable<Category> All
        {
            get { return context.Categories; }
        }

        public IQueryable<Category> AllIncluding(params Expression<Func<Category, object>>[] includeProperties)
        {
            IQueryable<Category> query = context.Categories;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Category Find(int id)
        {
            return context.Categories.Find(id);
        }

        public void InsertOrUpdate(Category category)
        {
            if (category.Id == default(int))
            {
                // New entity
                context.Categories.Add(category);
            }
            else
            {
                // Existing entity
                context.Entry(category).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            Category category = context.Categories.Find(id);
            context.Categories.Remove(category);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public IEnumerable<string> FindCategories(string criteria, int limit)
        {
            return context.Categories.
                 Where(c => c.CategoryName.ToLower().Contains(criteria.ToLower())).
                 Take(limit).
                 Select(c => c.CategoryName);
        }
    }
    public interface ICategoryRepository
    {
        IQueryable<Category> All { get; }
        IQueryable<Category> AllIncluding(params Expression<Func<Category, object>>[] includeProperties);
        Category Find(int id);
        void InsertOrUpdate(Category category);
        void Delete(int id);
        void Save();
        IEnumerable<string> FindCategories(string criteria, int limit);
    }
}